package com.wanmait.community.controller;

import com.wanmait.community.aop.OperationLogInfo;
import com.wanmait.community.entity.Unit;
import com.wanmait.community.service.UnitService;
import com.wanmait.community.util.AjaxResult;
import com.wanmait.community.util.JWTUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("admin/unit")
public class UnitController {
    @Resource
    private UnitService unitService;
    @GetMapping("list")
    public AjaxResult list() {
        List<Unit> unitList = unitService.findAll();
        return AjaxResult.success().put("unitList", unitList);
    }
    @OperationLogInfo("添加单元")
    @PostMapping("insert")
    public AjaxResult insert(@Validated @RequestBody Unit unit, HttpServletRequest request) {
        String token = request.getHeader("token");
        Integer adminId = Integer.parseInt(JWTUtils.getAudience(token));
        unit.setCreatBy(adminId);
        unit.setUpdateBy(adminId);
        return AjaxResult.success(unitService.save(unit));
    }
    @GetMapping("selectUnitNameAndBuildingIdByUnit")
    public AjaxResult selectUnitNameAndBuildingIdByUnit(String unitName, Integer buildingId) {
        Unit unit = unitService.selectUnitNameAndBuildingIdByUnit(new Unit().setUnitName(unitName).setBuildingId(buildingId));
        return AjaxResult.success().put("unit",unit);
    }
    @GetMapping("{buildingId}")
    public AjaxResult getUnitByBuildingId(@PathVariable Integer buildingId) {
        List<Unit> unitList = unitService.findUnitByBuildingId(buildingId);
        return AjaxResult.success().put("unitList", unitList);
    }
    @GetMapping("selectUnitById")
    public AjaxResult getUnitById(Integer id) {
        Unit unit = unitService.getById(id);
        return AjaxResult.success().put("unit", unit);
    }
}
